﻿using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiWrite.Application.Command;

namespace WMS.WebApiWrite.Application.Commandhandler
{
    /// <summary>
    /// 处理 <see cref="AddStoragelocationInfoCommand"/> 新增库位信息命令的处理器
    /// </summary>
    public class AddStoragelocationInfoCommandHandler : IRequestHandler<AddStoragelocationInfoCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<StoragelocationInfo> storagelocationRepository;
        private static readonly Random random = new Random();

        /// <summary>
        /// 构造函数，注入库位信息仓储
        /// </summary>
        /// <param name="storagelocationRepository">库位信息仓储接口</param>
        public AddStoragelocationInfoCommandHandler(IBaseRepository<StoragelocationInfo> storagelocationRepository)
        {
            this.storagelocationRepository = storagelocationRepository;
        }

        /// <summary>
        /// 生成唯一的库位编码
        /// 格式：KWBH+4位随机数（例如：KWBH1234）
        /// </summary>
        /// <returns>返回唯一的库位编码</returns>
        private string GenerateUniqueStoragelocationCode()
        {
            string code;
            int maxAttempts = 100; // 最大尝试次数，防止无限循环
            int attempts = 0;

            do
            {
                // 生成4位随机数（1000-9999）
                int randomNumber = random.Next(1000, 10000);
                code = $"KWBH{randomNumber}";

                attempts++;
                if (attempts >= maxAttempts)
                {
                    // 如果尝试次数过多，使用时间戳确保唯一性
                    code = $"KWBH{DateTime.Now:HHmmss}";
                    break;
                }

            } while (storagelocationRepository.GetAll().Where(x => !x.IsDeleted).Any(x => x.StoragelocationCode == code)); // 只检查未删除的记录

            return code;
        }

        /// <summary>
        /// 处理 <see cref="AddStoragelocationInfoCommand"/> 新增库位信息命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult<bool>> Handle(AddStoragelocationInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 自动生成唯一的库位编码（格式：KWBH+4位随机数）
                var storagelocationCode = GenerateUniqueStoragelocationCode();

                // 创建库位信息实体
                var storagelocationInfo = new StoragelocationInfo
                {
                    StoragelocationCode = storagelocationCode, // 使用自动生成的编码
                    StoragelocationName = request.StoragelocationDTO.StoragelocationName,
                    StoragelocationCapacity = request.StoragelocationDTO.StoragelocationCapacity,
                    StoragelocationState = request.StoragelocationDTO.StoragelocationState,
                    StoragelocationContent = request.StoragelocationDTO.StoragelocationContent,
                    StoragelocationScore = request.StoragelocationDTO.StoragelocationScore,
                    SupervisorId = request.StoragelocationDTO.SupervisorId,
                    IsDeleted = false, // 新建数据默认未删除
                    DataStatus = request.StoragelocationDTO.DataStatus, // 数据状态：1草稿 2已提交
                    CreateName = request.StoragelocationDTO.OperatorName,
                    CreateTime = DateTime.Now
                };

                // 执行新增操作
                var result = await storagelocationRepository.AddAsync(storagelocationInfo);

                if (result > 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增成功,
                        Message = $"新增库位信息成功，库位编码：{storagelocationCode}",
                        Data = true
                    };
                }
                else
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增失败,
                        Message = "新增库位信息失败",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiResultEnum.新增失败,
                    Message = $"新增库位信息异常：{ex.Message}",
                    Data = false
                };
            }
        }
    }
}
